package jp.co.mapion.conf;

import java.io.IOException;
import java.io.InputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public final class ConfigFileReader {

	private static final String SETTING_FILE = "mapion-conf.xml";

	private static String config = "conf.properties";

	private static String hostsDir = "hosts";

	static {
		init();
	}

	private ConfigFileReader() {

	}

	public static void init() {

		InputStream conf = ConfigFileReader.class.getResourceAsStream("/" + SETTING_FILE);
		if (conf == null) {
			return;
		}

		try {
			DocumentBuilderFactory fact = DocumentBuilderFactory.newInstance();
			DocumentBuilder builder = fact.newDocumentBuilder();
			Document doc = builder.parse(conf);

			NodeList childs = doc.getChildNodes();
			if (childs.item(0).getNodeType() == Node.ELEMENT_NODE) {
				Element root = (Element) childs.item(0);
				if ("config".equals(root.getTagName())) {
					NodeList nodeList = childs.item(0).getChildNodes();
					for (int i = 0, s = nodeList.getLength(); i < s; i++) {
						if (nodeList.item(i).getNodeType() == Node.ELEMENT_NODE) {
							Element e = (Element) nodeList.item(i);
							if ("conf".equals(e.getTagName())) {
								config = e.getChildNodes().item(0).getNodeValue();
							} else if ("hostsDir".equals(e.getTagName())) {
								hostsDir = e.getChildNodes().item(0).getNodeValue();
							}
						}
					}
				}
			}
		} catch (DOMException e) {
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static String getConfig() {
		return config;
	}

	public static String getHostsDir() {
		return hostsDir;
	}
}
